package com.sso.controller;

import com.google.common.base.Strings;
import com.sso.cache.RedisClientTemplate;
import com.sso.common.MD5;
import com.sso.service.SsoService;
import com.sso.util.SSOUtil;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by yangjianbo on 2016/10/10.
 */
@Controller
@RequestMapping("sso")
public class SsoController {

    private Logger logger =  Logger.getLogger(SsoController.class);

    @Autowired
    private SsoService ssoService;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam  String username,
                        @RequestParam  String password,
                        @RequestParam(required = false)  String clientAgent,
                        @RequestParam(required = false)  String clientIp,
                        @RequestParam(required = false)  String referer){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String client_agent = Strings.isNullOrEmpty(clientAgent)==true?request.getHeader("user-agent"):clientAgent;//获取浏览器信息
        String referer_uri=Strings.isNullOrEmpty(referer)==true?request.getHeader("Referer"):referer;
        String client_ip=Strings.isNullOrEmpty(clientIp)==true?SSOUtil.getIpAddr(request):clientIp;
        String userSecret= SSOUtil.KEY_HEAD+ MD5.MD5Encode(client_ip+client_agent);//根据客户端生成的秘钥
        password=MD5.MD5Encode(password);
        //将userSecret放入缓存并设置过期时间
        String userId=ssoService.login(username,password);
        logger.info("*****************************当前登录用户id："+userId);
        redisClientTemplate.set(userSecret,userId);
        redisClientTemplate.expire(userSecret,SSOUtil.KEY_EXPIRE);
        return referer_uri;
    }

    @RequestMapping(value = "out",method = RequestMethod.POST)
    @ResponseBody
    public String out(@RequestParam(required = false)  String clientAgent,
                      @RequestParam(required = false)  String clientIp){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String client_agent = Strings.isNullOrEmpty(clientAgent)==true?request.getHeader("user-agent"):clientAgent;//获取浏览器信息
        String client_ip= Strings.isNullOrEmpty(clientIp)==true?SSOUtil.getIpAddr(request):clientIp;
        String userSecret=SSOUtil.KEY_HEAD+MD5.MD5Encode(client_ip+client_agent);//根据客户端生成的秘钥
        //清楚客户端密钥，达到单点退出状态
        redisClientTemplate.del(userSecret);
        return "success";
    }

//    @RequestMapping(value = "get",method = RequestMethod.POST)
//    @ResponseBody
//    public String getUserInfo(@RequestParam String userSecret){
//
//        //从缓存拿出用户标识
//        String userId= (String)redisClientTemplate.get(userSecret);
//        logger.info("*****************************当前用户id："+userId);
//        if(userId==null){
//            return null;
//        }else {
//            redisClientTemplate.expire(userSecret,SSOUtil.KEY_EXPIRE);
//            return userId;
//        }
//    }

    @RequestMapping(value = "get",method = RequestMethod.POST)
    @ResponseBody
    public String getUserInfo(@RequestParam String clientIp,@RequestParam String clientAgent){

        //从缓存拿出用户标识
        String userSecret=SSOUtil.KEY_HEAD+MD5.MD5Encode(clientIp+clientAgent);//根据客户端生成的秘钥
        String userId= (String)redisClientTemplate.get(userSecret);
        logger.info("*****************************当前用户id："+userId);
        if(userId==null){
            return null;
        }else {
            redisClientTemplate.expire(userSecret,SSOUtil.KEY_EXPIRE);
            return userId;
        }
    }

}
